import {
  getuserSign,
  scoreRecord,
  getUserGiftList,
  getSignInfo,
} from "../api/index";
import { store } from "../../store/index";

Page({
  data: {
    signDays: 0, // 已签到天数
    canSignToday: true, // 今天是否可以签到
    userInfo: {},
    pageData: [],
    weekDays: [
      { name: "周一", signed: false },
      { name: "周二", signed: false },
      { name: "周三", signed: false },
      { name: "周四", signed: false },
      { name: "周五", signed: false },
      { name: "周六", signed: false },
      { name: "周日", signed: false },
    ],
  },

  onLoad() {
    this.setData({
      userInfo: store.userInfo,
    });
    this.getSignInStatus();
    this.getUserGiftList();
  },

  // 获取签到状态
  getSignInStatus() {
    getSignInfo().then((res) => {
      const { seriesSign:signDays, sign } = res.result;

      const todaySign = sign === '否' ? false : true

      // 获取当前是星期几（0-6，0代表周日）
      const today = new Date().getDay();
      // 将周日的0转换为7，使其与我们的数组对应
      const currentDay = today === 0 ? 7 : today;

      // 更新周签到状态
      const updatedWeekDays = this.data.weekDays.map((day, index) => {
        // index + 1 代表周几（1-7）
        const dayNumber = index + 1;
        
        // 计算从当前日期往前数的天数是否在连续签到范围内
        const isSigned = dayNumber <= currentDay && dayNumber > (currentDay - signDays);
        // 如果是当天且已签到，也标记为true
        const isTodaySigned = dayNumber === currentDay && todaySign;
        
        return {
          ...day,
          signed: isSigned || isTodaySigned,
        };
      });

      this.setData({
        signDays,
        canSignToday: !todaySign,
        weekDays: updatedWeekDays,
      });
    });
  },
  async getUserGiftList() {
    const data = await getUserGiftList({ pageNo: 1, pageSize: 1000 });
    this.setData({
      pageData: data.result.records,
    });
  },

  // 执行签到
  handleSignIn() {
    if (!this.data.canSignToday) {
      wx.showToast({
        title: "今日已签到",
        icon: "none",
      });
      return;
    }

    getuserSign().then((res) => {
      wx.showToast({
        title: "签到成功",
        icon: "success",
      });
      this.getSignInStatus(); // 刷新签到状态
    });
  },
  handleExchange(e) {
    wx.showModal({
      title: "提示",
      content: "确定兑换吗？",
      success: async (res) => {
        if (res.confirm) {
          await scoreRecord(e.currentTarget.dataset.item.id);
          wx.showToast({
            title: "兑换成功",
            icon: "success",
          });
          this.getUserGiftList();
          store.getUserInfo().then((res) => {
            this.setData({
              userInfo: res,
            });
          });
        }
      },
    });
  },
});
